import React from 'react';
import './approveList.less';
import { Breadcrumb, Icon, Button, Table, Modal, Input, Select, Pagination, message ,Row,Col,DatePicker,Form,Checkbox,AutoComplete,InputNumber,Upload } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';
import noRepeat from '../commonFunction/noRepeat';
import convertCurrency from '../commonFunction/convertCurrency';
import getFormatDate from '../commonFunction/getFormatData';
import moment from 'moment';
const { TextArea } = Input;
const config = new Config();
const FormItem = Form.Item;
const Option = Select.Option;
const { RangePicker } = DatePicker;
const userInfo = JSON.parse(sessionStorage.getItem('UserInfo')); //用户信息
const root = userInfo.root;
class AfterApproveList1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,//模态框
            applyList: [],//申请列表
            record:{},//单条列表
            applycount: 0,//申请列表条数
            pageindex:1,//当前页码
            selectionList:[[],[],[],[]],//筛选列表
            selectedProduct:'',//筛选产品
            selectedUmbrellaName:'',//筛选平台
            channelname:'',//账户名
            dateStr:['',''],//申请时间
            date:[undefined,undefined],
            dateStr1:['',''],//审批时间，
            date1:[undefined,undefined],
            dateStr2:['',''],//拨款时间，
            date3:[undefined,undefined],
            ModalAllDataUpdates:[{},{}],//模态框展示数据
            authTreeOfOne:{},//小工具权限
            fileList: [],//图片列表
            previewVisible: false,//预览图片
            previewImage: '',//预览图片
        }
    }
    componentWillMount(){
        console.log(userInfo.auth);
        if(userInfo.auth){
            if(userInfo.auth['橘色小工具']){
                this.setState({
                    authTreeOfOne:userInfo.auth['橘色小工具']
                },()=>{
                    console.log(this.state.authTreeOfOne['/payrequest/updatemoney']);
                })
            }
        }

    }
    componentDidMount() {
        //筛选列表
        let selectionList=[[],[],[],[]];
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/findsource`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            // data:{ user:sessionStorage.getItem('token'),},
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const List = data.data;
                    if (List.length > 0) {
                        List.forEach((ele, i) => {
                            selectionList[0].push(ele.product);  //产品
                            selectionList[1].push(ele.umbrellaname);//平台
                            selectionList[2].push(ele.channelname);//账户名
                            selectionList[3].push(ele.requestpeople);//申请人
                        });
                        this.setState({
                            selectionList:[noRepeat(selectionList[0]),noRepeat(selectionList[1]),noRepeat(selectionList[2]),noRepeat(selectionList[3]),]
                        },()=>{
                            console.log(this.state.selectionList);
                        })
                    }

                }
            }
        });
        this.getBannerList(1);
    }

    //banner详细信息对话框（新增/编辑）
    showBannerModal(record) {
        if(record) {
            this.setState({
                record,
                visible: true,
            },()=>{
                const{record}=this.state;
                this.getApplyShowingData1(record.product,record.umbrellaname,record.requesttime.slice(0,10));
            });
        }
    }

    //通过或驳回
    handleSureGiveMoney(){
        //       修改申请单状态
        // id,state 1 申请中、2 已通过、3 已拨款、4 已驳回
        this.props.form.validateFields((err, values)=>{
            if(!values.Filedata){
                message.info('请上传拨款凭证!',1);
                return;
            }
            if(!err){
                let refundimg=[];
                if(values.Filedata.length){
                    values.Filedata.forEach(item=>{
                        refundimg.push(item.response ? item.response.name : item.name);
                    })
                }
                $.ajax({
                    url: `${config.juseLittleTool}/payrequest/updatemoney`,
                    type: "post",
                    async: true,
                    headers: {
                        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
                    },
                    data:{
                        //user:sessionStorage.getItem('token'),
                        id:this.state.record.id,
                        state:3,
                        appropriationimg:JSON.stringify(refundimg),//图片路径
                    },
                    success: data => {
                        console.log(data);
                        if (data.code === 200) {
                            //state true:通过   false :驳回
                            this.setState({
                                visible: false,
                            });
                            message.info('拨款成功!',2);
                            const { pageindex,dateStr,dateStr1,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
                            this.getBannerList(pageindex,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
                        } else {
                            message.error(`${data.mes} 请返回重新操作`, 2);
                        }
                    }
                });
            }
        });
    }
    //获取申请列表
    getBannerList(pageindex,requesttime,examinetime,appropriationtime,product,budget,channelname) {
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/findlist`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                //user:sessionStorage.getItem('token'),
                pagesize:15,
                pageindex,
                requesttime,//申请时间，
                examinetime,//审批时间，
                appropriationtime,//拨款时间，
                product,//产品
                budget,//平台
                channelname,//账户名
                state:10,//标志已审
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    const applyList = data.data.rows;
                    if (applyList.length > 0) {
                        applyList.forEach((ele, i) => {
                            ele.index = i + 1;
                        });
                        this.setState({
                            applyList,
                            applycount: data.data.count,
                        });
                    }else{
                        this.setState({
                            applyList:[],
                            applycount: 0,
                        });
                    }
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //筛选查询
    doSearch(){
        this.setState({
            pageindex:1
        });
        const { dateStr,dateStr1,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
    }
    //分页
    changePage(pageindex) {
        this.setState({
            pageindex
        });
        const { dateStr,dateStr1,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        this.getBannerList(pageindex,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
    }
    //日期筛选方法
    changeDate(date, dateStr) {
        this.setState({
            dateStr,
            date,
        });
        this.setState({
            pageindex:1
        });
        const { dateStr1,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
    }
    //日期筛选方法
    changeDate1(date1, dateStr1) {
        this.setState({
            dateStr1,
            date1,
        });
        this.setState({
            pageindex:1
        });
        const { dateStr,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
    }
    //日期筛选方法
    changeDate2(date2, dateStr2) {
        this.setState({
            dateStr2,
            date2,
        });
        this.setState({
            pageindex:1
        });
        const { dateStr1,dateStr, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,channelname);
    }
    //生日禁用
    disabledDate(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }
    //筛选方法
    handleApplyState(state,value){
        this.setState({
            pageindex:1
        });
        const { dateStr,dateStr1,dateStr2, selectedProduct,selectedUmbrellaName,channelname}=this.state;
        console.log(state);
        if(state===1){
            this.setState({
                selectedProduct:value,
            })
            this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),value,selectedUmbrellaName,channelname);
        }else if(state===2){
            this.setState({
                selectedUmbrellaName:value,
            })
            this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,value,channelname);
        }else{
            this.setState({
                channelname:value,
            })
            this.getBannerList(1,JSON.stringify(dateStr),JSON.stringify(dateStr1),JSON.stringify(dateStr2),selectedProduct,selectedUmbrellaName,value);
        }
    }
    //获取申请展示数据
    getApplyShowingData1(product, umbrellaname, time,){
        $.ajax({
            url: `${config.juseLittleTool}/payrequest/findhistory`,
            type: "post",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
            },
            data:{
                //user:sessionStorage.getItem('token'),
                product,//产品
                umbrellaname,//平台，渠道商
                requesttime:time,
            },
            success: data => {
                console.log(data);
                if (data.code === 200) {
                    this.setState({
                        ModalAllDataUpdates:data.data
                    },)
                } else {
                    message.error(`${data.mes} 请返回重新操作`, 2);
                }
            }
        });
    }
    //预览图片对话框
    previewImg(file){
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview(){
        this.setState({ previewVisible: false })
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        // let isLt10M = file.size / 1024 / 1024 < 10;
        // if (!isLt10M) {
        //     message.config({ top: 50 });
        //     message.error('您上传的图片大小必须小于10MB！');
        // }
        // return isIMG && isLt10M;
        return isIMG ;
    }
    render() {
        const columns = [
            {
                title: '申请时间',
                dataIndex: 'requesttime',
                width:150,
            },{
                title: '审批时间',
                dataIndex: 'examinetime',
                width: 100,
            },{
                title: '拨款时间',
                dataIndex: 'appropriationtime',
                width: 100,
            },
            {
                title: '产品',
                dataIndex: 'product',
                width: 100,
            },{
                title: '平台',
                dataIndex: 'umbrellaname',
                width: 100,
            }, {
                title: '账户名',
                dataIndex: 'channelname',
                width: 100
            },{
                title: '申请状态',
                dataIndex: 'approvalstatus',
                width: 100,
                render:text=><span style={{color:text===1?'':text===3?'green':text===4?'red':''}}>{text===1?'申请中':text===2?'已通过':text===3?'已拨款':text===4?'已驳回':''}</span>
            },  {
                title: '申请人',
                dataIndex: 'requestpeople',
                width: 100
            }, {
                title: '操作',
                width: 100,
                render: (text, record) => (
                    <div>
                        <Button  type="primary" onClick={() => this.showBannerModal(record)}>查看</Button>
                    </div>
                )
            }
        ];
        const { getFieldDecorator, } =this.props.form;
        const formItemLayout = { labelCol: { span: 10 }, wrapperCol: { span: 14 }, };
        const{record,selectionList,ModalAllDataUpdates,authTreeOfOne,fileList,previewVisible,previewImage,}=this.state;
        return (
            <div className='goods-label clearfix'>
               <div>
                    {/*面包屑*/}
                    < Breadcrumb separator=">" >
                        <Breadcrumb.Item>橘色小工具</Breadcrumb.Item>
                        <Breadcrumb.Item>已审中心</Breadcrumb.Item>
                        <Breadcrumb.Item>费用审批</Breadcrumb.Item>
                    </Breadcrumb >
                    {/*筛选条*/}
                    <div style={{marginTop:'40px'}} className="clearfix">
                        <Row>
                            <Col span={6}>
                                申请时间:&nbsp;&nbsp;&nbsp;
                                <RangePicker placeholder={['请选择日期', '请选择日期']}
                                             onChange={this.changeDate.bind(this)}
                                             format='YYYY-MM-DD'
                                             value={this.state.date}
                                             style={{width:'180px'}}
                                             disabledDate={(val) => this.disabledDate(val)}
                                />
                            </Col>
                            <Col span={6}>
                               审批时间:&nbsp;&nbsp;&nbsp;
                                <RangePicker placeholder={['请选择日期', '请选择日期']}
                                             onChange={this.changeDate1.bind(this)}
                                             format='YYYY-MM-DD'
                                             value={this.state.date1}
                                             style={{width:'180px'}}
                                             disabledDate={(val) => this.disabledDate(val)}
                                />
                            </Col>
                            <Col span={6}>
                                拨款时间:&nbsp;&nbsp;&nbsp;
                                <RangePicker placeholder={['请选择日期', '请选择日期']}
                                             onChange={this.changeDate2.bind(this)}
                                             format='YYYY-MM-DD'
                                             value={this.state.date2}
                                             style={{width:'180px'}}
                                             disabledDate={(val) => this.disabledDate(val)}
                                />
                            </Col>
                        </Row>
                        <Row style={{marginTop:'20px'}}>
                            <Col span={6}>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;产品:&nbsp;&nbsp;&nbsp;
                                <Select  style={{width:'180px'}} onChange={this.handleApplyState.bind(this,1)} defaultValue="">
                                    <Option value='' >全部</Option>
                                    {selectionList[0].map(item=><Option value={item} key={item}>{item}</Option>)}
                                </Select>
                            </Col>
                            <Col span={6}>
                                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;平台:&nbsp;&nbsp;&nbsp;
                                <Select  style={{width:'180px'}} onChange={this.handleApplyState.bind(this,2)} defaultValue="">
                                    <Option value='' >全部</Option>
                                    {selectionList[1].map(item=><Option value={item} key={item}>{item}</Option>)}
                                </Select>
                            </Col>
                            <Col span={6}>
                                &nbsp;&nbsp;&nbsp;&nbsp;账户名:&nbsp;&nbsp;&nbsp;
                                <Select  style={{width:'180px'}} onChange={this.handleApplyState.bind(this,3)} defaultValue="">
                                    <Option value='' >全部</Option>
                                    {selectionList[2].map(item=><Option value={item} key={item}>{item}</Option>)}
                                </Select>
                            </Col>
                            <Col span={2}>
                                <Button type="primary" onClick={this.doSearch.bind(this)}>查询</Button>
                            </Col>
                        </Row>
                    </div>
                    <div className='allgoods-table clearfix' style={{marginTop:'40px'}}>
                        <Table
                            rowKey="index"
                            className="floor-table"
                            columns={columns}
                            dataSource={this.state.applyList}
                            pagination={false}
                            bordered
                        />
                    </div>
                    <div className='goods-label-let'>
                        <div className="floor-ppagi">
                            {
                                this.state.applycount == 0?
                                    <p className="floor-ppagip">
                                        共{this.state.applycount}条记录
                                    </p> :
                                    <p className="floor-ppagip">
                                        当前显示
                                        {15*(this.state.pageindex-1)+1}—
                                        {15*this.state.pageindex < this.state.applycount ? 15*this.state.pageindex : this.state.applycount}条记录，
                                        共{this.state.applycount}条记录
                                    </p>
                            }
                            <Pagination showQuickJumper current={this.state.pageindex} total={this.state.applycount || 1} defaultPageSize={15} onChange={this.changePage.bind(this)} />
                        </div>
                    </div>
                    <Modal
                        className="little-tool-modal-middle"
                        title="付款申请单"
                        visible={this.state.visible}
                        footer={null}
                        onCancel={()=>{this.setState({visible:false})}}
                        maskClosable={false}
                    >
                        <Row>
                            <Col span={7} offset={1}>
                                产品：{record.product}
                            </Col>
                            <Col span={7} offset={1}>
                                平台：{record.umbrellaname}
                            </Col>
                            <Col span={7} offset={1}>
                                账户名:{record.channelname}
                            </Col>
                        </Row>
                        <h3 className="my-apply-title-middle">平台联系方式</h3>
                        <Row>
                            <Col span={11} offset={1}>
                                姓名:{record.name?record.name:' --'}
                            </Col>
                            <Col span={11} offset={1}>
                                手机号码:{record.phone?record.phone:' --'}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={23} offset={1}>
                                公司名称:{record.company?record.company:' --'}
                            </Col>
                        </Row>
                        <h3 className="my-apply-title-middle">数据情况</h3>
                        <div >
                            <Row>
                                <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>近五天投放情况</Col>
                            </Row>
                            <Row>
                                <Col span={4} offset={1}>消费：</Col>
                                <Col span={3} >￥{ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0}</Col>
                                <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].consumptionmoney?ModalAllDataUpdates[0].consumptionmoney:0)}</Col>
                                <Col span={4}>总进线：</Col>
                                <Col span={4}>{ModalAllDataUpdates[0].coillnsum?ModalAllDataUpdates[0].coillnsum:0}</Col>
                            </Row>
                            <Row>
                                <Col span={4} offset={1}>平均进线成本：</Col>
                                <Col span={3} >￥{ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0}</Col>
                                <Col span={4} >{convertCurrency(ModalAllDataUpdates[0].averagelinecost?ModalAllDataUpdates[0].averagelinecost:0)}</Col>
                                <Col span={4}>产出比：</Col>
                                <Col span={4}>{ModalAllDataUpdates[0].outputratio?ModalAllDataUpdates[0].outputratio:0}</Col>
                            </Row>
                            <Row>
                                <Col span={10} offset={1} style={{color:'#aaa',marginTop:'10px'}}>历史数据</Col>
                            </Row>
                            <Row>
                                <Col span={4} offset={1}>消费：</Col>
                                <Col span={3} >￥{ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0}</Col>
                                <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].consumptionmoney?ModalAllDataUpdates[1].consumptionmoney:0)}</Col>
                                <Col span={4}>总进线：</Col>
                                <Col span={4}>{ModalAllDataUpdates[1].coillnsum?ModalAllDataUpdates[1].coillnsum:0}</Col>
                            </Row>
                            <Row>
                                <Col span={4} offset={1}>平均进线成本：</Col>
                                <Col span={3} >￥{ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0}</Col>
                                <Col span={4} >{convertCurrency(ModalAllDataUpdates[1].averagelinecost?ModalAllDataUpdates[1].averagelinecost:0)}</Col>
                                <Col span={4}>产出比：</Col>
                                <Col span={4}>{ModalAllDataUpdates[1].outputratio?ModalAllDataUpdates[1].outputratio:0}</Col>
                            </Row>
                        </div>
                        <h3 className="my-apply-title-middle">申请事宜（平台概述及销售主管投放建议）</h3>
                        <Row>
                            <Col span={22} offset={1} className="little-tool-textarea" style={{background:'#ddd',padding:'5px',borderRadius:'5px'}}>
                                {record.affairs}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={8} offset={1}>
                                收款账户名：{record.inforname}
                            </Col>
                            <Col span={8} >
                                付款方式：{record.paymethod==0?'银行卡':'支付宝'}
                            </Col>

                        </Row>
                        <Row>
                            <Col span={8} offset={1}>
                                开户行:{record.openingbank}
                            </Col>
                            <Col span={7} >
                                支行:{record.subbranch}
                            </Col>
                            <Col span={8} >
                                银行卡号：{record.account}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={23} offset={1}>
                                付款项目：{record.payproject}
                            </Col>
                        </Row>
                        <Row style={{marginTop:'10px'}}>
                            <Col span={8} offset={1}>
                                付款金额：{record.paymoney}
                            </Col>
                            <Col span={7} >
                                申请人：{record.requestpeople}
                            </Col>
                            <Col  span={8} >
                                要求付款时间: {record.paytime}
                            </Col>
                        </Row>
                        <Row>
                            <Col span={23} offset={1}>
                                <p>填单拍照：</p>
                                {
                                record.imgURL?(JSON.parse(record.imgURL)).length ? (JSON.parse(record.imgURL)).map((item,i)=>{
                                    return <a href={config.Filepath + item} target="_blank" key={i} style={{marginRight:'20px'}}>
                                        <img src={config.Filepath +item} style={{ height: "100px", width: "200px" }} />
                                    </a>
                                }):'未上传图片':''
                            }
                            </Col>
                        </Row>
                        {((root||authTreeOfOne['/payrequest/updatemoney'])&&(record.approvalstatus===2))?
                            <Row>
                            <Col span={10} >
                                <FormItem {...formItemLayout} label="上传拨款凭证" style={{ minHeight: '120px', marginBottom: 0 }}>
                                    {getFieldDecorator('Filedata', {
                                        valuePropName: 'fileList', getValueFromEvent: this.normFile.bind(this),
                                        rules: [{ required: true, message: '请上传拨款凭证' }],
                                    })(
                                        <Upload
                                            method="post"
                                            accept="image/*"
                                            name="Filedata"
                                            action={config.UploadFile + "/uploadpageimg"}
                                            beforeUpload={this.beforeUpload.bind(this)}
                                            listType="picture-card"
                                            className="upload-list-inline"
                                            onPreview={this.previewImg.bind(this)}
                                            showUploadList={{showPreviewIcon: true, showRemoveIcon:true }}
                                        >
                                            {(fileList.length >= 5) ?'':<div>
                                                <Icon type="plus" />
                                                <div className="ant-upload-text">点击上传图片</div>
                                            </div>}
                                        </Upload>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>:''}
                        { record.approvalstatus===3?
                            <Row>
                                <Col span={23} offset={1}>
                                    <p>拨款凭据照片：</p>
                                    {
                                        record.appropriationimg?(JSON.parse(record.appropriationimg)).length ? (JSON.parse(record.appropriationimg)).map((item,i)=>{
                                            return <a href={config.Filepath + item} target="_blank" key={i} style={{marginRight:'20px'}}>
                                                <img src={config.Filepath +item} style={{ height: "100px", width: "200px" }} />
                                            </a>
                                        }):<span>未上传凭证</span>:<span>未上传凭证</span>
                                    }
                                </Col></Row>:''}
                        <div style={{textAlign:'center'}}>
                            <Button style={{cursor:'default'}}>{record.approvalstatus===2?'已通过':record.approvalstatus===3?'已拨款':'已驳回'}</Button>
                            {((root||authTreeOfOne['/payrequest/updatemoney'])&&(record.approvalstatus===2))?<Button type="primary" style={{marginLeft:'10px'}} onClick={this.handleSureGiveMoney.bind(this)}>确定拨款</Button>:''}
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}
const AfterApproveList = Form.create()(AfterApproveList1);
export default AfterApproveList;
